package com.zmn.mcc.admin.controller.staff.role;

import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.request.RequestUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.mcc.business.interfaces.role.RoleStaffBService;
import com.zmn.mcc.model.entity.role.McRoleStaff;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @author heguanghua
 * @since 2020/05/11 13:39
 */
@Controller
@RequestMapping("/staff/role/modify/")
public class StaffRoleModifyController extends StaffRoleBaseController {

    @Resource
    private RoleStaffBService roleStaffBService;


    /**
     * 新增员工授权
     */
    @RequestMapping("add")
    @ResponseBody
    public ResponseDTO add(HttpServletRequest request, HttpServletResponse response,
                           @RequestParam(value = "keyId", defaultValue = "0") Integer staffId,
                           @RequestParam(value = "roleIds", defaultValue = "0") String roleIds) {

        String ip = RequestUtil.getRequestIp(request);
        if (NumberUtil.isNullOrZero(staffId)) {
            return ResponseDTO.fail("没有找到部门");
        }
        if (StringUtil.isBlank(roleIds)) {
            return ResponseDTO.fail("未指定授权角色");
        }
        return roleStaffBService.addRoleStaff(staffId, StringUtil.split(roleIds, Integer.class), getLoginStaff(), ip);
    }

    /**
     * 移除用户角色
     */
    @RequestMapping("cancel")
    @ResponseBody
    public ResponseDTO cancel(HttpServletRequest request, HttpServletResponse response,
                                    @RequestParam(value = "ids", defaultValue = "") String ids) {

        String ip = RequestUtil.getRequestIp(request);
        if (StringUtil.isBlank(ids)) {
            return ResponseDTO.fail("未指定要取消对此用户已授权的角色");
        }

        Integer staffId = 0;
        List<Integer> roleIds = new ArrayList<>();
        List<String> groups = StringUtil.split(ids, GlobalConsts.SPLITER_DEFAULT, String.class);
        for(String group: groups) {
            List<Integer> idid = StringUtil.split(group, GlobalConsts.SPLITER_UNDERLINE, Integer.class);
            McRoleStaff roleStaff = new McRoleStaff();
            staffId = idid.get(0);
            roleIds.add(idid.get(1));
        }
        return roleStaffBService.deleteRoleStaff(staffId, roleIds, getLoginStaff(), ip);
    }
}
